package cn.swing.his.operation.webapi.controller;

import cn.swing.his.common.web.JsonResult;
import cn.swing.his.common.web.ResponseCode;
import cn.swing.his.operation.service.IMsmService;
import cn.swing.his.operation.webapi.config.RandomUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.plaf.nimbus.State;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    private IMsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @ApiOperation(value = "发送手机验证码")
    @GetMapping("/send")
    public JsonResult sendCode(String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(StringUtils.hasText(code)) {
            return JsonResult.ok();
        }
        //如果从redis获取不到
        //生成验证码
        code = RandomUtils.getSixBitRandom();


        //整合腾讯云短信服务进行发送
        boolean flag = msmService.send(phone, code);
        if (flag) {
            //生成验证码放到redis里面，设置有效时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return JsonResult.ok();
        }
        return JsonResult.failed(ResponseCode.BAD_REQUEST,"发送短信失败");
    }
}